package patrol.mobile.com.mobilepatrol.fragment;


import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.dl7.recycler.adapter.BaseQuickAdapter;
import com.dl7.recycler.listener.OnRecyclerViewItemClickListener;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.Unbinder;
import okhttp3.Call;
import patrol.mobile.com.mobilepatrol.R;
import patrol.mobile.com.mobilepatrol.activity.office.DeductionActivity;
import patrol.mobile.com.mobilepatrol.activity.office.DepartmentExaminationDetailsActivity;
import patrol.mobile.com.mobilepatrol.adapter.FuWuQuAndFenJuAdapter;
import patrol.mobile.com.mobilepatrol.adapter.KeShiAdapter;
import patrol.mobile.com.mobilepatrol.api.Urls;
import patrol.mobile.com.mobilepatrol.bean.DateBean;
import patrol.mobile.com.mobilepatrol.bean.KeShiListBean;
import patrol.mobile.com.mobilepatrol.utils.DatePickerUtil03;
import patrol.mobile.com.mobilepatrol.utils.GsonUtil;
import patrol.mobile.com.mobilepatrol.utils.TimeUtils;
import patrol.mobile.com.mobilepatrol.utils.net.HttpCallBack;
import patrol.mobile.com.mobilepatrol.utils.net.HttpSender;
import patrol.mobile.com.mobilepatrol.view.CallBack;
import patrol.mobile.com.mobilepatrol.widget.MySpinner;

import static patrol.mobile.com.mobilepatrol.activity.CommonListActivity.ROWS;

/**
 * 绩效汇总+服务区+分局的科室
 */
public class JiXiaoHuiZongFragment extends BaseFragment {

    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    private static final String TAG = "JiXiaoHuiZongFragment";
    @BindView(R.id.mySpinner)
    MySpinner mySpinner;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.mySpinner2)
    MySpinner mySpinner2;
    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.ll_item)
    LinearLayout llItem;
    Unbinder unbinder;

    private String mParam1;
    private String mParam2;
    private BaseQuickAdapter mAdapter;
    private int page = 1;
    private List<KeShiListBean> keShiListBeans;


    public JiXiaoHuiZongFragment() {
        // Required empty public constructor
    }


    public static JiXiaoHuiZongFragment newInstance(String param1, String param2) {
        JiXiaoHuiZongFragment fragment = new JiXiaoHuiZongFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_ke_shi;
    }

    @Override
    protected void initData() {
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        if (mParam1.equals("0")) {
            mAdapter = new KeShiAdapter(getActivity());
        } else {
            mAdapter = new FuWuQuAndFenJuAdapter(getActivity());
        }
        recyclerView.setAdapter(mAdapter);

        if (mParam1.equals("0")) {
            tvTime.setVisibility(View.VISIBLE);
            llItem.setVisibility(View.GONE);
            requestFirstData(true, TimeUtils.dateStringYM(System.currentTimeMillis()).replace("-", ""));//科室列表
        } else if (mParam1.equals("1")) {
            tvTime.setVisibility(View.GONE);
            llItem.setVisibility(View.VISIBLE);
            requestSecondData(true, TimeUtils.dateStringY(System.currentTimeMillis()), "第1季度");//收费服务区
        } else {
            tvTime.setVisibility(View.GONE);
            llItem.setVisibility(View.VISIBLE);
            requestThirdData(true, TimeUtils.dateStringY(System.currentTimeMillis()), "第1季度");//分局
        }
    }

    @Override
    protected void initListener() {
        final List<String> years = new ArrayList<>();
        final List<String> periods = new ArrayList<>();
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1;
        int period = calendar.get(Calendar.MONTH) / 3 + 1;
        tvTime.setText(TimeUtils.dateStringYM(System.currentTimeMillis()));
        Log.i(TAG, "initListener: " + "-" + year + "-" + month + "-" + period);

        for (int i = 0; i < 5; i++) {
            years.add(year - i + "");
        }
        for (int i = 1; i < 5; i++) {
            periods.add("第" + i + "季度");
        }
        mySpinner.setmDatas(years, new MySpinner.CallBack() {
            @Override
            public void onSelect(int postion) {
                if (mParam1.equals("1")) {
                    requestSecondData(true, years.get(postion), mySpinner2.getmText().getText().toString());
                } else if (mParam1.equals("2")) {
                    requestThirdData(true, years.get(postion), mySpinner2.getmText().getText().toString());
                }
            }
        });

        mySpinner2.setmDatas(periods, new MySpinner.CallBack() {
            @Override
            public void onSelect(int postion) {
                if (mParam1.equals("1")) {
                    requestSecondData(true, mySpinner.getmText().getText().toString(), periods.get(postion));
                } else if (mParam1.equals("2")) {
                    requestThirdData(true, mySpinner.getmText().getText().toString(), periods.get(postion));
                }
            }
        });
        mAdapter.setOnItemClickListener(new OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                if (mParam1.equals("0")) {
                    DeductionActivity.show(getActivity(), 1, keShiListBeans.get(position).getId());
                } else if (mParam1.equals("1")) {//收费服务区
                    DepartmentExaminationDetailsActivity.show(getActivity(), mParam1, keShiListBeans.get(position).getId(), "各科室对收费服务片区考核");
                } else if (mParam1.equals("2")) {//分局
                    DepartmentExaminationDetailsActivity.show(getActivity(), mParam1, keShiListBeans.get(position).getId(), "各科室对分局考核");
                }
            }
        });
    }

    private void requestFirstData(final boolean isRefresh, String time) {
        if (isRefresh) {
            page = 1;
        } else {
            page++;
        }
        HttpSender sender = new HttpSender(getActivity(), baseUrl, Urls.ORG_CHECK_LIST);//科室列表
        HashMap<String, String> map = new HashMap<>();
        map.put("period", time);
        map.put("page", page + "");
        map.put("rows", ROWS + "");
        sender.requestPost(map, new HttpCallBack(sender) {
            @Override
            public void onError(String code, Call call, Exception e) {

            }

            @Override
            public void onResponse(String code, String response) {
                JsonParser jp = new JsonParser();
                JsonObject jo = jp.parse(response).getAsJsonObject();

                JsonArray listArray = jo.getAsJsonArray("list");
                int rows = jo.get("rows").getAsInt();
                keShiListBeans = GsonUtil.jsonToList(listArray.toString(), KeShiListBean.class);
                setData(page, isRefresh, keShiListBeans, rows);
            }
        });
    }

    private void requestSecondData(final boolean isRefresh, String year, String period) {
        if (isRefresh) {
            page = 1;
        } else {
            page++;
        }
        HttpSender sender = new HttpSender(getActivity(), baseUrl, Urls.ORG_CHECK_AREA_LIST);//收费服务区
        HashMap<String, String> map = new HashMap<>();
        map.put("period", year + "年" + period);
        map.put("page", page + "");
        map.put("rows", ROWS + "");
        sender.requestPost(map, new HttpCallBack(sender) {
            @Override
            public void onError(String code, Call call, Exception e) {

            }

            @Override
            public void onResponse(String code, String response) {
                JsonParser jp = new JsonParser();
                JsonObject jo = jp.parse(response).getAsJsonObject();

                JsonArray listArray = jo.getAsJsonArray("list");
                int rows = jo.get("rows").getAsInt();
                keShiListBeans = GsonUtil.jsonToList(listArray.toString(), KeShiListBean.class);
                setData(page, isRefresh, keShiListBeans, rows);
            }
        });
    }

    private void requestThirdData(final boolean isRefresh, String year, String period) {
        if (isRefresh) {
            page = 1;
        } else {
            page++;
        }
        HttpSender sender = new HttpSender(getActivity(), baseUrl, Urls.ORG_CHECK_ORG_LIST);//分局
        HashMap<String, String> map = new HashMap<>();
        map.put("period", year + "年" + period);
        map.put("page", page + "");
        map.put("rows", ROWS + "");
        sender.requestPost(map, new HttpCallBack(sender) {
            @Override
            public void onError(String code, Call call, Exception e) {

            }

            @Override
            public void onResponse(String code, String response) {
                JsonParser jp = new JsonParser();
                JsonObject jo = jp.parse(response).getAsJsonObject();

                JsonArray listArray = jo.getAsJsonArray("list");
                int rows = jo.get("rows").getAsInt();
                keShiListBeans = GsonUtil.jsonToList(listArray.toString(), KeShiListBean.class);
                setData(page, isRefresh, keShiListBeans, rows);
            }
        });
    }

    public void setData(int page, boolean isRefresh, List data, int rows) {
        final int size = data == null ? 0 : data.size();
        if (isRefresh) {
            mAdapter.updateItems(data);
        } else {
            int totalPage;
            if ((int) Math.ceil(rows / ROWS) == 0) {
                totalPage = 1;
            } else {
                totalPage = (int) Math.ceil(rows / ROWS);
            }
            if (page == totalPage) {
                if (page == 1) {
                    mAdapter.updateItems(data);
                    mAdapter.enableLoadMore(false);//加载loading gone掉
                } else {
                    mAdapter.addItems(data);
                    mAdapter.noMoreData();
                }
            } else {
                mAdapter.addItems(data);
//                mAdapter.enableLoadMore(false);//加载loading gone掉
                mAdapter.loadComplete();//本次加载完成
            }
        }
    }

    @OnClick(R.id.tv_time)
    public void onViewClicked() {
        DatePickerUtil03.getInstance().show(getActivity(), new CallBack<DateBean>() {
            @Override
            public void onBack(DateBean dateBean) {
                tvTime.setText(dateBean.getmYear() + "-" + dateBean.getmMonth());
                requestFirstData(true, "" + dateBean.getmYear() + dateBean.getmMonth());//科室列表
            }
        });
    }
}
